package com.handpay.nocardpay.baselibrary.pay.qrcodepay.view.fragment;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseErrorInfo;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.main.widget.PayChannelInfo;
import com.handpay.nocardpay.baselibrary.pay.qrcodepay.model.bean.QrcodeRspBean;
import com.handpay.nocardpay.baselibrary.pay.qrcodepay.presenter.QrCodePresenter;
import com.handpay.nocardpay.baselibrary.pay.qrcodepay.view.IQrcodePayView;
import com.handpay.nocardpay.baselibrary.utils.ArithUtil;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.xys.libzxing.zxing.encoding.EncodingUtils;

import java.util.HashMap;

/**
 * Created by lyang on 2017/8/11.
 */

public class QrCodePayFragment extends BaseFragment implements IQrcodePayView {
    public static final String QR_CODE_PAY_TYPE = "QR_CODE_PAY_TYPE";
    public static final String AMOUNT_KEY = "AMOUNT_KEY";
    private View mFakeStatusBar;
    private ImageView icon_pay_channel_iv, qrcode_iv;
    private TextView qr_code_tips_tv;
    private double mAmount = 0;
    private TextView tv_amount;
    private String tradeType;
    private BitmapDrawable ic_launcher;
    private QrCodePresenter qrCodePresenter;

    public static QrCodePayFragment newInstance(String payType, double amount) {
        Bundle args = new Bundle();
        args.putString(QR_CODE_PAY_TYPE, payType);
        args.putDouble(AMOUNT_KEY, amount);
        QrCodePayFragment fragment = new QrCodePayFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_qr_code_pay;
    }

    @Override
    public String getFragmentTitle() {
        if (tradeType.equals(PayChannelInfo.ALIPAY_CODE)) {
            return getString(R.string.alipay_qr_code);
        } else if (tradeType.equals(PayChannelInfo.WECHATPAY_CODE)) {
            return getString(R.string.wechatpay_qr_code);
        } else if (tradeType.equals(PayChannelInfo.UNIPAY_SCANNER_CODE)) {
            return getString(R.string.union_qrcode);
        } else if (tradeType.equals(PayChannelInfo.QQ_PAY_CODE)) {
            return getString(R.string.qq_wallet);
        } else {
            return " ";
        }
    }

    @Override
    public void initView(View view) {
        tradeType = getArguments().getString(QR_CODE_PAY_TYPE);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(toolbar, true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _mActivity.finish();
            }
        });
        mFakeStatusBar = view.findViewById(R.id.fake_status_bar);

        qrcode_iv = (ImageView) view.findViewById(R.id.qrcode_iv);
        icon_pay_channel_iv = (ImageView) view.findViewById(R.id.icon_pay_channel_iv);
        qr_code_tips_tv = (TextView) view.findViewById(R.id.qr_code_tips_tv);


        if (PayChannelInfo.ALIPAY_CODE.equals(tradeType)) {
            icon_pay_channel_iv.setImageResource(R.drawable.home_icon_alipay);
            qr_code_tips_tv.setText(R.string.alipay_qr_code_tips);
        } else if (PayChannelInfo.WECHATPAY_CODE.equals(tradeType)) {
            icon_pay_channel_iv.setImageResource(R.drawable.home_icon_wechatpay);
            qr_code_tips_tv.setText(R.string.wechatpay_qr_code_tips);
            setTvTitleBackgroundColor(0x53C66A);
        } else if (PayChannelInfo.QQ_PAY_CODE.equals(tradeType)) {
            icon_pay_channel_iv.setImageResource(R.drawable.home_icon_qq_pay);
            qr_code_tips_tv.setText(R.string.qqwallet_qr_code_tips);
        } else if (PayChannelInfo.UNIPAY_SCANNER_CODE.equals(tradeType)) {
            icon_pay_channel_iv.setImageResource(R.drawable.home_icon_unipay_scanner);
            qr_code_tips_tv.setText(R.string.union_qr_code_tips);
        }
        tv_amount = (TextView) view.findViewById(R.id.tv_amount);


    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mAmount = this.getArguments().getDouble(AMOUNT_KEY, 0d);
        ic_launcher = (BitmapDrawable) _mActivity.getResources().getDrawable(R.mipmap.ic_launcher);
        tv_amount.setText(CommonUtils.formatMoneyDouble(ArithUtil.div(mAmount, 100d)));
//        String url;
//        String host;
//        if (NoCardPayConfig.isTesting) {
//            host = ClientEngine.getInstance().QR_CODE_PAY_URL_TEST;
//        } else {
//            host = "https://scan.handpay.cn/hpayMicroWap/scanpay/index.htm?";
//        }
//        String merchantCode = AccountUtils.getMerchantCode(_mActivity);
//        String secretkey = "HaN_yIn_scan_Pay";
//        String sign = new MD5().getMD5ofStr(merchantCode + Double.valueOf(mAmount).intValue() + secretkey).toLowerCase();
//        url = host + "channel=" + ClientEngine.getInstance().CHANNEL +
//                "&merchantCode=" + merchantCode +
//                "&amount=" + Double.valueOf(mAmount).intValue() +
//                "&clientChannel=" + NoCardPayConfig.CLIENTCHANNEL +
//                "&clientVersion=v" + ClientEngine.getInstance().VERSION +
//                "&sign=" + sign;
        qrCodePresenter = new QrCodePresenter(_mActivity);
        qrCodePresenter.setQrcodePayView(this);
        getQrCodeUrl();
    }

    public void setTvTitleBackgroundColor(@ColorInt int color) {

        mFakeStatusBar.setBackgroundColor(color);
    }

    /**
     * get qrcode url
     */
    private void getQrCodeUrl() {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.AMOUNT, SecureManager.getInstance().des(String.valueOf(Double.valueOf(mAmount).intValue()), 1, null));
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, ClientEngine.getInstance().CLIENTCHANNEL);
        if (PayChannelInfo.ALIPAY_CODE.equals(tradeType)) {
            paramers.put(BaseProtocolKey.TRADETYPE, NoCardPayConstant.TRADETYPE_ALISCANPAY);
        } else if (PayChannelInfo.WECHATPAY_CODE.equals(tradeType)) {
            paramers.put(BaseProtocolKey.TRADETYPE, NoCardPayConstant.TRADETYPE_WECHATSCANPAY);
        } else if (PayChannelInfo.QQ_PAY_CODE.equals(tradeType)) {
            paramers.put(BaseProtocolKey.TRADETYPE, NoCardPayConstant.TRADETYPE_QQWALLET);
        } else if (PayChannelInfo.UNIPAY_SCANNER_CODE.equals(tradeType)) {
            paramers.put(BaseProtocolKey.TRADETYPE, NoCardPayConstant.TRADETYPE_UNIONSCANPAY);
        }
        paramers.put(BaseProtocolKey.CLIENTVERSION, "v" + ClientEngine.getInstance().VERSION);
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        paramers.put(BaseProtocolKey.KEY_ADDRESS, address);
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String location = latitude.toString() + "," + longtitude.toString();
        paramers.put(BaseProtocolKey.KEY_LOCATION, location);
        qrCodePresenter.getQrcodeUrl(paramers, true);
    }

    @Override
    public void showErrorAlert(BaseErrorInfo baseErrorInfo) {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.dialog_title), baseErrorInfo.errMessage, false, _mActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                _mActivity.finish();
            }
        });
    }

    @Override
    public void getQrCodeResult(QrcodeRspBean qrcodeRspBean) {
        String qrCodeUrl = SecureManager.getInstance().des(qrcodeRspBean.getQrCodeUrl(), 0, null);
        if (!TextUtils.isEmpty(qrCodeUrl)) {
            Bitmap mQRCodeBitmap = EncodingUtils.createQRCode(qrCodeUrl, CommonUtils.dp2px(180), CommonUtils.dp2px(180), ic_launcher.getBitmap());
            qrcode_iv.setImageBitmap(mQRCodeBitmap);
        } else {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.dialog_title), "获取二维码失败!", false, _mActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    _mActivity.finish();
                }
            });
        }

    }
}
